// pages/product/product.js
import Toast from '../../lib/vant-weapp/toast/toast';
let WxParse = require("../../lib/wxParse/wxParse.js");
const jeegot = require('../../utils/jeegot.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {    
    isLogin: false,
    couponShow: false,
    serviceShow: false,
    cartList: [],
    product: {},
    serviceList: [{
      id: 1,
      title: "48小时快速退款",
      desc: "收到退货包裹并确认无误后，将在48小时内办理退款，退款将原路返回，不同银行处理时间不同，预计1-5个工作日到账。"
    },
    {
      id: 2,
      title: "满88元免邮费",
      desc: "单笔订单金额（不含运费），大陆地区满88元免邮，不满88元收取10元邮费；港澳台地区满500元免邮，不满500元收取30元运费；海外地区以下单页提示运费为准。"
    },
    {
      id: 3,
      title: "官方自营品牌",
      desc: "官方原创生活类电商品牌，所有商品均为官方自营，品质保证。"
    },
    {
      id: 4,
      title: "国内部分地区无法配送",
      desc: "不支持省份: 台湾、香港、澳门、新疆"
    }],
    
    show: false,
    skuList: [],
    skuGroup: {},
    findSku: true,
    defaultSku: undefined,
    selectedProp: [],
    selectedPropObj: {},
    propKeys: [],
    allProperties: [],
    productNum:1,

    recommend: [],
    hot: [],
    couponList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '商品详情',
    })

    let me = this
    jeegot.getProduct({id:options.id}).then(data=>{
      me.setData({product: data, skuList: data.productSkuList, recommend: data.recommendList, hot: data.hotList});
      WxParse.wxParse('productDetail', 'html', this.data.product.contentHtmlView, me, 0);
      me.groupSkuProp();
    })

    jeegot.getCouponList({}).then(data =>{
      me.setData({couponList: data})
    })

    // 读取购物车
    let cartList = wx.getStorageSync("cartList");
    if (cartList) {
      this.setData({
        cartList: cartList
      })
    }
    
  },

  /**
   * 根据skuList进行数据组装
   */
  groupSkuProp: function() {
    var skuList = this.data.skuList;

    if (skuList.length == 0) {
      //此处使用商品价格库存构造一个无属性的sku对象
      var mySku = {
        price: this.data.product.price,
        originPrice: this.data.product.originPrice,
        stock: this.data.product.stock
      }
      this.setData({defaultSku: mySku})
      return;
    }

    var skuGroup = {};//所有的规格名(包含规格名下的规格值集合）对象，如 {"颜色"：["金色","银色"],"内存"：["64G","256G"]}
    var allProperties = [];//所有SKU的属性值集合，如 ["颜色:金色;内存:64GB","颜色:银色;内存:64GB"]
    var propKeys = [];//所有的规格名集合，如 ["颜色","内存"]

    for (var i = 0; i < skuList.length; i++) {

      //找到和商品价格一样的那个SKU，作为默认选中的SKU
      var defaultSku = this.data.defaultSku;
      var isDefault = false;
      if (!defaultSku && skuList[i].price == this.data.price) { 
        defaultSku = skuList[i];
        isDefault = true;
        this.setData({
          defaultSku: defaultSku
        });
      }

      var properties = skuList[i].skuProperties; //如：版本:公开版;颜色:金色;内存:64GB
      allProperties.push(properties);
      var propList = properties.split(";"); // 如：["版本:公开版","颜色:金色","内存:64GB"]

      var selectedPropObj = this.data.selectedPropObj;
      for (var j = 0; j < propList.length; j++) {

        var propval = propList[j].split(":"); //如 ["版本","公开版"]
        var props = skuGroup[propval[0]]; //先取出 规格名 对应的规格值数组

        //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
        if (isDefault) {
          propKeys.push(propval[0]);
          selectedPropObj[propval[0]] = propval[1];
        }

        if (props == undefined) {
          props = []; //假设还没有版本，新建个新的空数组
          props.push(propval[1]); //把 "公开版" 放进空数组
        } else {
          if (!this.array_contain(props, propval[1])) { //如果数组里面没有"公开版"
            props.push(propval[1]); //把 "公开版" 放进数组
          }
        }
        skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
      }
      this.setData({
        selectedPropObj: selectedPropObj,
        propKeys: propKeys
      });
    }
    this.parseSelectedObjToVals();
    this.setData({
      skuGroup: skuGroup,
      allProperties: allProperties
    });
  },

  //将已选的 {key:val,key2:val2}转换成 [val,val2]
  parseSelectedObjToVals: function() {
    var selectedPropObj = this.data.selectedPropObj;
    var selectedProperties = "";
    var selectedProp = [];
    for (var key in selectedPropObj) {
      selectedProp.push(selectedPropObj[key]);
      selectedProperties += key + ":" + selectedPropObj[key] + ";";
    }
    selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1);
    this.setData({
      selectedProp: selectedProp
    });

    var findSku = false;
    for (var i = 0; i < this.data.skuList.length; i++) {
      if (this.data.skuList[i].skuProperties == selectedProperties) {
        findSku = true;
        this.setData({
          defaultSku: this.data.skuList[i],
        });
        break;
      }
    }
    this.setData({
      findSku: findSku
    });
  },

  //点击选择规格
  toChooseItem: function(e) {
    var val = e.currentTarget.dataset.val;
    var key = e.currentTarget.dataset.key;
    var selectedPropObj = this.data.selectedPropObj;
    selectedPropObj[key] = val;
    this.setData({
      selectedPropObj: selectedPropObj
    });
    this.parseSelectedObjToVals();
  },

  //判断数组是否包含某对象
  array_contain: function(array, obj) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == obj) //如果要求数据类型也一致，这里可使用恒等号===
        return true;
    }
    return false;
  },

  showPopup() {
    this.setData({ show: true });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    // 加载商品详情数据
    /**
    * WxParse.wxParse(bindName , type, data, target,imagePadding)
    * 1.bindName绑定的数据名(必填)
    * 2.type可以为html或者md(必填)
    * 3.data为传入的具体数据(必填)
    * 4.target为Page对象,一般为this(必填)
    * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
    */
    //let that = this;
    //WxParse.wxParse('productDetail', 'html', this.data.product.detail, that, 0);

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.product.title,
      path: '/pages/product/product?id=' + this.data.product.id
    }
  },
  openIndexPage: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  openCoupon: function () {
    this.setData({
      couponShow: true
    })
  },
  closeCoupon: function () {
    this.setData({
      couponShow: false
    })
  },
  openAddress: function () {
    let that = this;
    wx.chooseLocation({
      success: function (res) {
        if(!res.address){
          return;
        }
        that.setData({
          'deliveryAddress.address': res.address
        })
      },
    })
  },
  openService: function () {
    this.setData({
      serviceShow: true
    })
  },
  closeService: function () {
    this.setData({
      serviceShow: false
    })
  },
  openCartPage: function () {
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  },
  toComment: function () {
    wx.navigateTo({
      url: '/pages/comment/comment?productId=' + this.data.product.id,
    })
  },
  toProduct: function (e) {
    let id = e.currentTarget.dataset.value.id;
    wx.navigateTo({
      url: '/pages/product/product?id=' + id
    })
  },
  clickTag: function (e) {
    let v = e.currentTarget.dataset.value;
    wx.navigateTo({
      url: '/pages/promotion/promotion?id=' + v.id + '&title=' + v.title
    });
  },
  previewThumb: function (e) {
    wx.previewImage({
      current: this.data.product.picUrl,
      urls: [this.data.product.picUrl]
    })
  },
  showSku: function (e) {
    this.setData({show: true})
  },
  closeSku: function (e) {
    this.setData({show: false})
  },
  onChange(e){
    console.log(e.detail);
    this.setData({productNum:e.detail.value})
  },
  buyNow: function () {

    if(!jeegot.isLogined()) {
      wx.navigateTo({
        url: '/pages/auth/tologin/tologin',
      })
      return;
    }

    if (!this.data.show) {
      this.setData({show:true})
    } else {
      if(this.data.skuList.length>0 && !this.data.findSku) {
        Toast("请选择规格");
        return;
      }
      // 跳转checkout页面
      wx.setStorageSync("checkoutProduct", this.data.product);
      wx.setStorageSync("checkoutProductSku", this.data.defaultSku);
      wx.setStorageSync("productNum", this.data.productNum);
      wx.navigateTo({
        url: '/pages/checkout/checkout?from=product',
      })
    }
  },
  addToCart: function () {

    if(!jeegot.isLogined()) {
      wx.navigateTo({
        url: '/pages/auth/tologin/tologin',
      })
      return;
    }

    if (!this.data.show) {
      this.setData({show:true})
    } else {
      // 添加至购物车 判断数量
      if(this.data.skuList.length>0 && !this.data.findSku) {
        Toast("请选择规格");
        return;
      }
      
      let cartList = this.data.cartList;

      var isExistInCart = false;
      var existIndex = 0;
      for(var i=0;i<cartList.length;i++) {
        var cartItem = cartList[i];
        if(cartItem.id == this.data.product.id) {
          isExistInCart = true;
          existIndex = i;
          break;
        }
      }
      if(isExistInCart) {
        var oldCount = cartList[existIndex].count;
        var newCount = oldCount + this.data.productNum;
        cartList[existIndex].count = newCount;
      }else {
        cartList.push({
          id: this.data.product.id,
          checked: true,
          picUrl: this.data.product.thumbUrl,
          title: this.data.product.title,
          spec: this.data.defaultSku ? this.data.defaultSku.skuName : "",
          count: this.data.productNum,
          maxNum: this.data.defaultSku.stock,
          price: this.data.defaultSku.price
        });
      }

      wx.setStorageSync("cartList", cartList);
      this.setData({cartList: cartList});
      Toast("加入购物车成功");
    }
  },
  toVip: function(){
    wx.navigateTo({
      url: '/pages/ucenter/vip/vip',
    })
  }
})